package com.kcs.fxmargin.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.action.form.ListOfForwardContractActionForm;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.ListOfForwardContractBO;
import com.kcs.fxmargin.service.ExportService;
import com.kcs.fxmargin.service.ListOfForwardContractService;

public class ListOfForwardContractAction extends FXAction {
	
	private Logger log = Logger.getLogger(Constant.LOG_FX);

	@Override
	public ActionForward process(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ListOfForwardContractActionForm bean = null;
		ListOfForwardContractBO bo = null;
		ListOfForwardContractService svc = null;
		LoginActionForm userInfo = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
		log.info("Begin : ListOfForwardContractAction : process");
		
		try{
			
			bean = (ListOfForwardContractActionForm)form;
			
			if(bean.getTranCode().equals("")){
				bean.resetForm();
			}else if(bean.getTranCode().equals("searchForwardContract")){
				
				if(validateSearchForwardContract(bean,request)){
					bo = new ListOfForwardContractBO();
					bo.setUser(bean.getUserLoginId());
					bo.setInCifNo(bean.getInCifNo());
					bo.setInCustomerName(bean.getInCustomerName());
					bo.setInAsOfDate(formatAsOfDate(bean.getInAsOfDate()));
					
					svc = new ListOfForwardContractService();
					bo = svc.getForwardContractList(bo);
					bean.setForwardContractList(bo.getForwardContractList());
					request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
				}
				
			}else if(bean.getTranCode().equals("printForwardContractList")){
				
				exportForwardContractListToExcel(bean.getForwardContractList(),bean.getInCifNo(),bean.getInCustomerName(),bean.getInAsOfDate(),userInfo.getUserName(),response);
				request.setAttribute(Constant.SHOW_RESULT, Constant.SHOW_RESULT);
				
			}else if(bean.getTranCode().equals("resetForm")){
				bean.resetForm();
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute(Constant.ERR_ATTR, e+"");
			
		}finally{
			if(bean != null){
				bean.setTranCode("");
			}
		}

		log.info("End : ListOfForwardContractAction : process");
		return mapping.findForward("listOfForwardContract");
	}
	
	private boolean validateSearchForwardContract(ListOfForwardContractActionForm bean, HttpServletRequest request)throws Exception{
		boolean result = true;
		
		log.info("Begin : ListOfForwardContractAction : validateSearchForwardContract");
		
		if (bean.getInCifNo().equals("") || bean.getInCustomerName().equals("") || bean.getInAsOfDate().equals("")) {
			request.setAttribute(Constant.ERR_ATTR, Constant.ERR_REQUIRED_COMPLETE);
			result = false;
		
		}else{
			if (!bean.getInAsOfDate().equals("")){
				if(commonUtils.checkDateFormat(bean.getInAsOfDate())){
					result = true;
				}else{
					request.setAttribute(Constant.ERR_ATTR, Constant.ERR_DATE_FORMAT);
					result = false;
				}
				
			}else{
				result = true;
			}
			
		}
		
		log.info("End : ListOfForwardContractAction : validateSearchForwardContract");
		return result;
	}
	
	private String formatAsOfDate(String date)throws Exception{
		String[] spl = null;
		String d = null;
		String m = null;
		String y = null;
		String result = date;
		
		if(date != null && !date.equals("")){
			spl = date.split("/");
			d = spl[0];
			m = spl[1];
			y = spl[2];
			
			result = y+"-"+m+"-"+d;
		}
		
		return result;
	}
	
	public void exportForwardContractListToExcel(List<ListOfForwardContractBO> fcList, String cifNo, String customerName, String asOfDate, String userName,HttpServletResponse response)throws Exception{

		ExportService service = new ExportService();		
		ServletOutputStream out = null;
        InputStream in = null;
        try {
        	byte[] result  = service.genListOfForwardContract(fcList, cifNo, customerName, asOfDate, userName);
            in = new ByteArrayInputStream(result);

            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + Constant.EXCEL_FORWARD_CONTRACT_FILENAME);
            out = response.getOutputStream();

            byte[] outputByte = new byte[result.length];
            int bytesRead;
            while ((bytesRead = in.read(outputByte, 0, result.length)) != -1) {
                out.write(outputByte, 0, bytesRead);
            }
            out.flush();
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
	}
	
	
	@SuppressWarnings("deprecation")
	public void exportForwardContractListToExcelBak(List<ListOfForwardContractBO> fcList, String cifNo, String customerName, String asOfDate, String userName,HttpServletResponse response)throws Exception{
		ServletOutputStream out = null;
		HSSFWorkbook workbook = null;
		HSSFSheet sheet = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		ListOfForwardContractBO fc = null;
		HSSFCellStyle style = null;
		HSSFFont font = null;
		
		log.info("Begin : ListOfForwardContractAction : exportForwardContractListToExcel");
		int rowCnt = 0;
		
		if(fcList != null && fcList.size()>0){
			workbook = new HSSFWorkbook();
			
			sheet = workbook.createSheet("List of FC");
			sheet.getPrintSetup().setLandscape(true);
			sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); 

			sheet.setFitToPage(true);
			sheet.getPrintSetup().setScale((short)100);
			//Criteria
			font = workbook.createFont();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style = workbook.createCellStyle();
			style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
			style.setFont(font);
			style.setWrapText(false);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("CIF No. : "+cifNo);
			cell.setCellStyle(style);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Customer Name : "+customerName);
			cell.setCellStyle(style);
			
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("As of Date : "+asOfDate);
			cell.setCellStyle(style);
			
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13));
			sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 13));
			sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 13));
			
			//-- Header cell style
			font = workbook.createFont();
			style = workbook.createCellStyle();
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setFont(font);
			style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style.setFillForegroundColor(new HSSFColor.AQUA().getIndex());
			
			//style.setFillBackgroundColor(new HSSFColor.AQUA().getIndex());
			
			rowCnt++;
			row = sheet.createRow(rowCnt++);
			cell = row.createCell(0, Cell.CELL_TYPE_STRING);
			cell.setCellValue("No.");
			cell.setCellStyle(style);
			cell = row.createCell(1, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Deal No.");
			cell.setCellStyle(style);
			cell = row.createCell(2, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Days to Mat");
			cell.setCellStyle(style);
			cell = row.createCell(3, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Mat Date");
			cell.setCellStyle(style);
			cell = row.createCell(4, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Client Buy/Sell");
			cell.setCellStyle(style);
			cell = row.createCell(5, Cell.CELL_TYPE_STRING);
			cell.setCellValue("CCY Pair");
			cell.setCellStyle(style);
			cell = row.createCell(6, Cell.CELL_TYPE_STRING);
			cell.setCellValue("FX Rate");
			cell.setCellStyle(style);
			cell = row.createCell(7, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Amt1");
			cell.setCellStyle(style);
			cell = row.createCell(8, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Amt2");
			cell.setCellStyle(style);
			cell = row.createCell(9, Cell.CELL_TYPE_STRING);
			cell.setCellValue("IM Required");
			cell.setCellStyle(style);
			cell = row.createCell(10, Cell.CELL_TYPE_STRING);
			cell.setCellValue("MTM Rate");
			cell.setCellStyle(style);
			cell = row.createCell(11, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Unrealized P/L (THB)");
			cell.setCellStyle(style);
			cell = row.createCell(12, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Deal Status");
			cell.setCellStyle(style);
			cell = row.createCell(13, Cell.CELL_TYPE_STRING);
			cell.setCellValue("Deal Type");
			cell.setCellStyle(style);
	

			for(int i=0; i<fcList.size(); i++){
				fc = fcList.get(i);
				int colCnt = 0;
				row = sheet.createRow(rowCnt++);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(i+1);
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getDealId());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getDayToMat());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getMatDate());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getBuySell());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getCcyPair());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getFxRate());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getAmt1());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getAmt2());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getImRequired());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getMtmRate());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getUnrealizedPL());
				cell.setCellStyle(style);
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getDealStatus());
				cell.setCellStyle(style);
				
				
				style = workbook.createCellStyle();
				style.setWrapText(false);
				style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
				cell = row.createCell(colCnt++, Cell.CELL_TYPE_STRING);
				cell.setCellValue(fc.getDealType());
				cell.setCellStyle(style);

			}
			

			
			HSSFRow rowTmp   = sheet.getRow(rowCnt-1); 
			java.util.Iterator<HSSFCell> it = row.cellIterator(); 
		    while(it.hasNext()){ 
			         HSSFCell cellTmp = it.next(); 
			         sheet.autoSizeColumn((short)cellTmp.getCellNum(),true); 
			 }
//			for(int s=0; s<14; s++){
//				sheet.autoSizeColumn((short)s,true);
//			}

			workbook.setPrintArea(0, 0, 13, 0, rowCnt-1);
			
			HSSFFooter footer = sheet.getFooter();
			footer.setLeft("Print by : "+userName);
			footer.setRight("Print Date : "+commonUtils.getcurrentDatetime());
			
			
			response.setHeader("Pragma", "no-cache");
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition", "attachment; filename="+Constant.EXCEL_FORWARD_CONTRACT_FILENAME);
						
			out = response.getOutputStream();
			workbook.write(out);
			out.flush();
			out.close();
			
			log.info("Export excel successfully.");
			
		}else{
			throw new Exception("Cannot export Excel: Data error.");
		}
		
		log.info("End : ListOfForwardContractAction : exportForwardContractListToExcel");
		 
	}

}
